<template>
  <template v-if="getShow">
    <div class="mb-8">
      <LoginFormTitle class="enter-x" />
      <Form class="p-4 enter-x" :model="formData" :rules="registerFormRules" ref="formRef">
        <FormItem name="alias" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.alias') }}</p>
          <Input
            class="fix-auto-fill"
            v-model:value="formData.alias"
            :placeholder="t('saasSys.login.enterprisePlaceholder')"
          />
        </FormItem>
        <FormItem name="name" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.enterprise') }}</p>
          <Input
            class="fix-auto-fill"
            v-model:value="formData.name"
            :placeholder="t('saasSys.login.enterprisePlaceholder')"
          />
        </FormItem>
        <FormItem name="industry" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.industry') }}</p>
          <Select
            class="fix-auto-fill"
            v-model:value="formData.industry"
            :placeholder="t('saasSys.login.industryPlaceholder')"
          >
            <SelectOption :key="industry.code" v-for="industry in industryList" :value="industry.name">{{
              industry.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem name="location" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.location') }}</p>
          <Select
            class="fix-auto-fill"
            v-model:value="formData.location"
            :placeholder="t('saasSys.login.locationPlaceholder')"
          >
            <SelectOption :key="location.code" v-for="location in locationList" :value="location.name">{{
              location.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem name="channel" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.channel') }}</p>
          <Select
            class="fix-auto-fill"
            v-model:value="formData.channel"
            :placeholder="t('saasSys.login.channelPlaceholder')"
          >
            <SelectOption :key="channel.code" v-for="channel in channelList" :value="channel.name">{{
              channel.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem name="userName" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.userName') }}</p>
          <Input
            class="fix-auto-fill"
            v-model:value="formData.userName"
            :placeholder="t('saasSys.login.userNamePlaceholder')"
          />
        </FormItem>
        <FormItem class="enter-x" name="password">
          <p class="login-tip">{{ t('saasSys.login.password') }}</p>
          <InputPassword v-model:value="formData.password" placeholder="请输入密码" @change="pwdChange" />
        </FormItem>
        <FormItem
          class="enter-x"
          name="checkPassword"
          :rules="[
            { required: true, message: '确认密码不能为空' },
            { validator: validatePass2, trigger: 'change' },
          ]"
        >
          <p class="login-tip">{{ t('saasSys.login.checkPassword') }}</p>
          <InputPassword v-model:value="formData.checkPassword" placeholder="请再次输入密码" />
        </FormItem>
        <FormItem name="phone" class="enter-x">
          <p class="login-tip">{{ t('saasSys.login.phone') }}</p>
          <Input
            class="fix-auto-fill"
            v-model:value="formData.phone"
            :placeholder="t('saasSys.login.phonePlaceholder')"
          />
        </FormItem>
        <FormItem name="privacy">
          <Checkbox v-model:checked="formData.privacy">阅读并同意</Checkbox>
          <a @click="handlePrivacy">《隐私声明》</a>
        </FormItem>
      </Form>
      <Button
        type="primary"
        class="enter-x"
        block
        @click="handleRegister"
        :loading="loading"
        :disabled="!formData.privacy"
      >
        {{ t('saasSys.login.registerButton') }}
      </Button>
      <Button block class="mt-4 enter-x" @click="handleBackLogin">
        {{ t('saasSys.login.returnButton') }}
      </Button>
    </div>
  </template>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, computed, watchEffect } from 'vue';
import LoginFormTitle from './LoginFormTitle.vue';
import { Form, Input, Button, Select, SelectOption, Checkbox, InputPassword } from 'ant-design-vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useLoginState, useFormValid, LoginStateEnum } from './useLogin';
import { getLabelList, registerSaaSUser } from '/@/api/sys/user';
import { useMessage } from '/@/hooks/web/useMessage';
import { registerFormRules } from './data';
import { Rule } from 'ant-design-vue/lib/form';

const FormItem = Form.Item;
const { t } = useI18n();
const { handleBackLogin, getLoginState } = useLoginState();
const { createMessage } = useMessage();
const industryList = ref([]);
const locationList = ref([]);
const channelList = ref([]);
const formRef = ref();
const loading = ref(false);

const formData = reactive({
  alias: '',
  name: '',
  industry: '',
  location: '',
  channel: '',
  userName: '',
  password: '',
  checkPassword: '',
  phone: '',
  privacy: false,
});

const { validForm } = useFormValid(formRef);

function adaptDifferentDevice() {
  if (document.documentElement.clientWidth < 2000 && document.documentElement.clientWidth > 1300) {
    document.body.style.zoom = 0.9;
  }

  if (document.documentElement.clientWidth < 1000) {
    document.body.style.zoom = 0.85;
  }
}
adaptDifferentDevice();
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER);
watchEffect(() => {
  if (getShow.value == true) {
    getLabelList().then((res) => {
      industryList.value = res.industry;
      locationList.value = res.location;
      channelList.value = res.channel;
    });
  }
});
const emit = defineEmits(['showPrivacy']);
const handlePrivacy = () => {
  emit('showPrivacy', true);
};

async function handleRegister() {
  try {
    loading.value = true;
    const data = await validForm();
    if (!data) return;

    const res = await registerSaaSUser(data);
    if (res) {
      createMessage.success('注册成功，请登录！');
      formRef.value.resetFields();
      handleBackLogin();
    } else {
      createMessage.error('注册失败，请重新注册！');
    }
  } catch (error) {
    createMessage.error('注册失败，请重新注册！');
  } finally {
    loading.value = false;
  }
}
const pwdChange = async () => {
  if (formData.checkPassword) {
    await formRef.value.validateFields(['checkPassword']);
  }
};
let validatePass2 = async (_rule: Rule, value: string) => {
  if (value && value !== formData.password) {
    return Promise.reject(new Error('请输入相同密码'));
  } else {
    return Promise.resolve();
  }
};
</script>

<style lang="less" scoped>
.login-tip {
  width: 500px;
  font-size: 12px;
  color: dimgray;
  margin-bottom: 5px;
}
</style>
